package com.jmu.posms.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jmu.posms.dao.PermissionMapper;
import com.jmu.posms.dao.RoleMapper;
import com.jmu.posms.dto.PermissionDto;
import com.jmu.posms.pojo.Permission;
import com.jmu.posms.pojo.Role;
import com.jmu.posms.pojo.User;
import com.jmu.posms.service.PermissionService;
import com.jmu.posms.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
    @Resource
    UserService userService;

    @Resource
    PermissionMapper permissionMapper;

    @Resource
    RoleMapper roleMapper;

    @Override
    public PermissionDto findAllPermissions (String id, Integer type){
        PermissionDto permissionDto = new PermissionDto();
        User user = userService.getById(id);

        String[] userRoles = StringUtils.split(user.getRoleId(), "|");

        if(userRoles!=null){
            for(String roleId : userRoles){
                //根据角色的id来获取权限
                Role role = null;
                try{
                    role = roleMapper.selectById(roleId);
                    //添加用户
                    permissionDto.addRole(role);
                }catch (Exception e){
                    log.info("角色id---"+roleId+"不存在！");
                }
                if(role!=null){
                    //分割该角色所有的权限id
                    String[] permissions = StringUtils.split(role.getPermissions(), "|");
                    if(permissions!=null){
                        //赋予权限
                        for (String permissionId : permissions) {
                            try{
                                Permission permission = permissionMapper.selectById(permissionId);
                                //类别与请求列表相同才添加
                                if(permission.getType().equals(type) || type.equals(2)){
                                    permissionDto.addPermission(permission);
                                    String[] urls = StringUtils.split(permission.getUrl(), "|");
                                    if(urls!=null){
                                        //添加权限路径
                                        for (String url : urls) {
                                            permissionDto.addUrl(url,permission.getPermissionName());
                                        }
                                    }
                                }
                            }catch (Exception e){
                                log.info("权限id----"+permissionId+"不存在");
                            }
                        }
                    }
                }

            }
        }
        return permissionDto;
    }
}
